<?php

namespace App\Service\User\v1_2_1;

use AlibabaCloud\Vcs\V20200515\VcsApiResolver;
use App\Cache\UserRemarkCache;
use App\Constants\ErrorCode;
use App\Constants\RecommendedGradeCode;
use App\Exception\ApiException;
use App\Helpers\RedisUtil;
use App\Model\PayOrder;
use App\Model\Service\CacheService;
use App\Model\Setting\SettingAppHidden;
use App\Model\User;
use App\Model\UserProfile;
use App\Model\UserScore;
use App\Model\UserTag;
use App\Model\UserTypeRule;
use App\Service\ServiceTrait\GetUserInfoTrait;
use App\Service\ServiceTrait\UserListTrait;
use App\Service\User\UserBaseService;
use Hyperf\DbConnection\Db;
use Hyperf\Cache\Annotation\Cacheable;
/**
 * 用户列表
 */
class UserListService extends UserBaseService
{
    use UserListTrait;

    public function handle()
    {
        //rec-精选，new-新人
        $type = $this->request->input('type', 'rec');
        // $appId = $this->request->input('appid', 1);
        $page = $this->request->input('page', 1);
        $this->request->input('version','1.0.0');

        $this->userId = $this->getUserId();

//        $userIds = array_diff(, config('busi.kefu_uid'));
        $userIds = array_diff($this->getUserList($type), config('busi.kefu_uid'));


        $start = ($page - 1) * $this->pageNum;
        $userIds = array_slice($userIds, $start, $this->pageNum);
//        shuffle($userIds);
        $usersInfo = UserProfile::getUsersProfile($userIds, false, true);
        $ret = ['list' => []];
        $imAccounts = User::getImAccounts($userIds);
        $nowTime = time();
        array_walk($usersInfo, function ($userProfile) use (&$ret, $imAccounts, $nowTime) {
            $item = $this->buildUserItem($userProfile, $this->userId, $imAccounts);
            $item['online_status'] = UserProfile::getOnlineStatusV2($userProfile['online'], $userProfile['updated_at'], $userProfile['gender']);
            $item['chat_type'] = $this->checkChatBefore($userProfile['user_id']) ? 1 : 2;
            // if($userProfile['gender'] ==0){
            //     $item['chat_type'] = 1;
            // }else{
            //     $item['chat_type'] = $this->checkChatBefore($userProfile['user_id']) ? 1 : 2;
            // }

            $item['remark'] = $this->userId != $userProfile['user_id'] ? (new UserRemarkCache())->getRemark($this->userId, $userProfile['user_id']) : '';

            $ret['list'][] = $item;
        });
        //自己的标签
        $this->packNewTags($ret['list'], $userIds, 'user');
        //喜欢的标签
        $this->packLoveTags($ret['list'], $userIds);
        // log_user_result($userId, $userIds);
        return $ret;
    }

    function checkChatBefore($chatUserId = 0)
    {
        return RedisUtil::get("chat_start_{$this->userId}_{$chatUserId}");
    }

    /**
     * 获取用户列表（不同类型）
     */
    function getUserList($type = 'rec')
    {
        switch ($type) {
            case 'rec':
//                $userIds = $this->getRecommendScoreUserId();
                $userIds = $this->getActiveUsersV2(500, $this->buildSelectWhere(true));
                break;
            default:
                $userIds = $this->getNewUsersV2(500, $this->buildSelectWhere(true));
                break;
        }
        return $userIds;
    }

    /**
     * @Cacheable(prefix="user_list", ttl=30,value="_#{limit}", listener="user_list")
     * 获取最新的用户
     */
    function getNewUsers($limit = 500, $profileWhere = [])
    {
        $channels = SettingAppHidden::getHiddeChannels(SettingAppHidden::FUNC_PUSH);
        $where = [
            ['status', '=', User::STATUS_OK],
            ['user_profile.role', '=', UserProfile::ROLE_USER],
            ['gender', 1],
            ['user.id','>',10]
        ];
        if ($profileWhere) $where = array_merge($where, $profileWhere);
        return Db::table('user_profile')->join('user', function ($join) {
            $join->on('user.id', '=', 'user_profile.user_id');
        })->whereNotIn('cur_channel', $channels)
            ->orderBy('online', 'desc')
            ->orderBy('user_profile.updated_at','desc')
            ->orderBy('user_id', 'desc')
            ->where($where)
            ->where(function ($query){
                $city = config('busi.limit_hidden_city_array');
                if(!empty($city)){
                    $query->whereNotIn('user_profile.locate_city',$city);
                }
            })
            ->limit($limit)->pluck('user_id')->toArray();
    }


    /**
     * @Cacheable(prefix="user_list_users", ttl=30,value="_#{limit}", listener="user_list_users")
     * 获取活跃用户
     */
    function getActiveUsers($limit = 500, $profileWhere = [])
    {
        $channels = SettingAppHidden::getHiddeChannels(SettingAppHidden::FUNC_PUSH);
        $where = [
            ['status', '=', User::STATUS_OK],
            ['user_profile.role', '=', UserProfile::ROLE_USER],
            ['gender', 1],
            ['user_profile.updated_at', '>=', date('Y-m-d', strtotime('-3 days'))],
            ['user.id','>',10]
        ];
        if ($profileWhere) $where = array_merge($where, $profileWhere);

        $userIds = Db::table('user_profile')->join('user', function ($join) {
            $join->on('user.id', '=', 'user_profile.user_id');
        })->whereNotIn('cur_channel', $channels)->orderBy('online', 'desc')
            ->where($where)
            ->where(function ($query){
                $city = config('busi.limit_hidden_city_array');
                if(!empty($city)){
                    $query->whereNotIn('user_profile.locate_city',$city);
                }
            })
            ->orderBy('online', 'desc')
            ->orderBy('user_profile.updated_at','desc')
            ->limit($limit)->pluck('user_id')->toArray();
        // shuffle($userIds);
        return $userIds;
    }

    /**
     * @Cacheable(prefix="user_list", ttl=30,value="_#{limit}", listener="user_list")
     * 获取最新的用户
     */
    function getNewUsersV2($limit = 500, $profileWhere = [])
    {
        $where = [
            ['status', '=', User::STATUS_OK],
            ['user_profile.role', '=', UserProfile::ROLE_USER],
            ['gender', 1],
            ['user.id','>',10]
        ];
        if ($profileWhere) $where = array_merge($where, $profileWhere);
        $userIds = Db::table('user_profile')->join('user', function ($join) {
                $join->on('user.id', '=', 'user_profile.user_id');
            })
            ->orderBy('online', 'desc')
            ->orderBy('user_profile.updated_at','desc')
            ->orderBy('user_id', 'desc')
            ->where($where)
            ->where(function ($query){
                $city = config('busi.limit_hidden_city_array');
                if(!empty($city)){
                    $query->whereNotIn('user_profile.locate_city',$city);
                }
            });

//        $userIds = (new SettingAppHidden())->getAppHiddenSubQuery($userIds);

        $userIds = $userIds->limit($limit)->pluck('user_id')->toArray();

        $excludeUsers = SettingAppHidden::getExcludeUsers();

        $userIds = array_diff($userIds, $excludeUsers);

        return $userIds;
    }

    /**
     * @Cacheable(prefix="user_list_users", ttl=30,value="_#{limit}", listener="user_list_users")
     * 获取活跃用户
     */
    function getActiveUsersV2($limit = 500, $profileWhere = [])
    {
        $where = [
            ['status', '=', User::STATUS_OK],
            ['user_profile.role', '=', UserProfile::ROLE_USER],
            ['gender', 1],
//            ['user_profile.updated_at', '>=', date('Y-m-d', strtotime('-3 days'))],
            ['user.id','>',10]
        ];
        if ($profileWhere) $where = array_merge($where, $profileWhere);

        $userIds = Db::table('user_profile')
            ->join('user', function ($join) {
                $join->on('user.id', '=', 'user_profile.user_id');
            })->orderBy('online', 'desc')
            ->where($where)
//            ->where(function ($query){
//                $city = config('busi.limit_hidden_city_array');
//                if(!empty($city)){
//                    $query->whereNotIn('user_profile.locate_city',$city);
//                }
//            })
            ->orderBy('online', 'desc')
            ->orderBy('user_profile.updated_at','desc');

//        $userIds = (new SettingAppHidden())->getAppHiddenSubQuery($userIds);

        $userIds = $userIds->limit($limit)->pluck('user_id')->toArray();

        $excludeUsers = SettingAppHidden::getExcludeUsers();
        $excludeUsers = [];
//        var_dump($excludeUsers);

        $userIds = array_diff($userIds, $excludeUsers);

        return $userIds;
    }
}
